#pragma once 
#include "net.hpp"
#include "message.hpp"

namespace yjz_rpc
{
    class CallBack
    {
    public:
        using ptr = std::shared_ptr<CallBack>;
        virtual void onMessage(const BaseConnection::ptr& conn, BaseMessage::ptr& msg) = 0;
    };

    template<class T>
    class CallBackT : public CallBack
    {
    public:
        using ptr = std::shared_ptr<CallBackT<T>>;
        using MessageCallBack = std::function<void(const BaseConnection::ptr&, std::shared_ptr<T>&)>;
        
        CallBackT(const MessageCallBack& hander) : _hander(hander) {}
        virtual void onMessage(const BaseConnection::ptr& conn, BaseMessage::ptr& msg) override
        {
            auto type_msg = std::dynamic_pointer_cast<T>(msg);
            _hander(conn, type_msg);
        }
    private:
        MessageCallBack _hander;
    };

    class Dispatcher
    {
    public:
        using ptr = std::shared_ptr<Dispatcher>;

        template<class T>
        void registerHandler(MType mtype, const typename CallBackT<T>::MessageCallBack& handler)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto cb = std::make_shared<CallBackT<T>>(handler);
            _handlers[mtype] = cb;
        }

        void onMessage(const BaseConnection::ptr& conn, BaseMessage::ptr& msg)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _handlers.find(msg->getMType());
            if (it != _handlers.end())
            {
                return it->second->onMessage(conn, msg);
            }
            LOG(LogLevel::ERROR) << "收到未知类型的消息！";
            conn->shutdown();
        }
    private:
        std::mutex _mutex;
        std::unordered_map<MType, CallBack::ptr> _handlers;
    };
}